package com.zmj.base.file.util;

import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@Slf4j
public class MinIoUntil {

    private MinioClient minioClient;

    public MinioClient getClient(String endpoint, String accessKey, String secretKey) {
        try {
            this.minioClient = new MinioClient(endpoint, accessKey, secretKey);
        } catch (Exception e) {
            log.error("获取Minio客户端失败",e);
        }
        return minioClient;
    }

    /**
     * 文件上传
     *
     * @param minioClient
     * @param bucketName
     * @param filePath
     * @param file
     * @return
     */
    public static String putFile(MinioClient minioClient, String endpoint, String bucketName, String filePath, MultipartFile file) {
        String viewPath = "";
        try {
//            InputStream input = file.getInputStream();
            ByteArrayInputStream bais = new ByteArrayInputStream(file.getBytes());
//            minioClient.putObject(bucketName, filePath, input, file.getSize(), file.getContentType());
            minioClient.putObject(bucketName, filePath, bais, Long.valueOf(bais.available()), null, null,
                    file.getContentType());
            bais.close();
            String url = minioClient.getObjectUrl(bucketName, filePath);
            viewPath = url;
        } catch (Exception e) {
            log.error("更新文件失败",e);
        }
        return viewPath;
    }
    /**
     * 文件删除
     *
     * @param minioClient
     * @param bucketName
     * @param filePath
     * @return
     */
    public void deleteFile(MinioClient minioClient, String bucketName, String filePath) {
        try {
            minioClient.removeObject(bucketName,filePath);
        } catch (Exception e) {
            log.error("删除文件失败",e);
        }
    }
}
